package com.kritsana_ding.startrax;

import ioio.lib.api.DigitalOutput;
import ioio.lib.api.Uart;
import ioio.lib.api.exception.ConnectionLostException;
import ioio.lib.util.BaseIOIOLooper;
import ioio.lib.util.IOIOLooper;
import ioio.lib.util.android.IOIOActivity;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.StrictMode;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

@SuppressLint("DefaultLocale")
public class Detial extends IOIOActivity implements OnInitListener,
		LocationListener {

	public Button button;
	public TextToSpeech myTTS;
	public int MY_DATA_CHECK_CODE = 0;

	public TextView textView_Name;
	public TextView textView_Status;
	public TextView textView_;
	public ScrollView sv;
	public ImageView imageView_Status;

	public LocationManager lm;

	public InputStream in_;
	public int success = 0;

	public String txt = "";

	public JSONObject json;

	public Handler handler1 = new Handler();
	public Handler handler2 = new Handler();
	public Handler handler3 = new Handler();

	boolean task_1 = false;
	public String formServer = "";

	public Runnable task1 = new Runnable() {
		@Override
		public void run() {
			if (task_1) {
				if (!formServer.equals("ERROR")) {
					try {
						json = new JSONObject(formServer);
						if (json.getString("Name").equals("KRITSANA")) {
							speakWords("hello "
									+ json.getString("Name").toLowerCase()
									+ "Welcome to star trax");
							Log.i("Name", json.getString("Name"));
							handler1.postDelayed(this, 5000);

							textView_Name.setText(json.getString("Name") + " "
									+ json.getString("Surname"));
							textView_Status.setText("Pass");

							txt = "Waiting GPS";
							setText(txt);
							imageView_Status.setImageDrawable(getResources()
									.getDrawable(R.drawable.checkmark));

						} else {
							textView_Name.setText(json.getString("Name")
									+ " Fail");
							speakWords("Failed, please contact");
							textView_Status.setText("Failed");
							imageView_Status.setImageDrawable(getResources()
									.getDrawable(R.drawable.no_entry));
							txt = "Waiting GPS";
							setText(txt);
						}

					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					task_1 = false;
				} else {
					task_1 = false;
				}
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.detials);

		// Permission StrictMode
		if (android.os.Build.VERSION.SDK_INT > 9) {
			StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
					.permitAll().build();
			StrictMode.setThreadPolicy(policy);
		}

		// check for TTS data
		Intent checkTTSIntent = new Intent();
		checkTTSIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
		startActivityForResult(checkTTSIntent, MY_DATA_CHECK_CODE);

		textView_Name = (TextView) findViewById(R.id.textViewName);
		textView_Status = (TextView) findViewById(R.id.textViewStatus);
		textView_ = (TextView) findViewById(R.id.textView4);
		sv = (ScrollView) findViewById(R.id.SV);
		imageView_Status = (ImageView) findViewById(R.id.imageView1);
		lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		button = (Button) findViewById(R.id.mybutton);

		button.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent sent = new Intent(getApplicationContext(), VDO.class);

				startActivity(sent);
				// overridePendingTransition(R.anim.slide_in_left,
				// R.anim.slide_out_left);
				overridePendingTransition(R.anim.slide_down, R.anim.slide_up);
				finish();
			}
		});

	}

	@SuppressLint("ResourceAsColor")
	class Looper extends BaseIOIOLooper {
		public DigitalOutput led_;

		public Uart uart_;
		public OutputStream out_;
		int counter = 0;
		int test = 0;
		Thread readThread = new readDataThread();// creates the read thread

		@Override
		public void setup() throws ConnectionLostException {
			try {
				led_ = ioio_.openDigitalOutput(0, true);

				uart_ = ioio_.openUart(40, 3, 9600, Uart.Parity.NONE,
						Uart.StopBits.ONE);
				out_ = uart_.getOutputStream();
				in_ = uart_.getInputStream();
				readThread.start();// Starts the thread

				setText("in setup");
				enableUi(true);
			} catch (ConnectionLostException e) {
				enableUi(false);
				throw e;
			}
		}

		@Override
		public void loop() throws ConnectionLostException {
			try {

				if (success == 5) {
					readThread.interrupt();// Ends the thread
					setText("Successful transmission\n" + txt);

					String url = "http://192.168.0.82/Driving/Details";

					List<NameValuePair> params = new ArrayList<NameValuePair>();
					params.add(new BasicNameValuePair("data", txt));

					String resultServer = getHttpPost(url, params);

					setText(resultServer);

					formServer = resultServer;

					task_1 = true;
					handler1.postDelayed(task1, 10);

					Thread.sleep(10);
					txt = "";
					success = 0;
				}

			} catch (InterruptedException e) {
				ioio_.disconnect();
			}
		}
	}

	@Override
	protected IOIOLooper createIOIOLooper() {
		return new Looper();
	}

	public void enableUi(final boolean enable) {
		runOnUiThread(new Runnable() {
			@Override
			public void run() {

			}
		});
	}

	public void setText(final String str) {
		runOnUiThread(new Runnable() {
			@Override
			public void run() {
				textView_.setText(str);
			}
		});
	}

	public class readDataThread extends Thread {
		@Override
		public void run() {
			while (true) {
				try {
					int i = in_.read();
					// String aString = Integer.toString(i);
					txt += (char) i + "";

					if (i == 10) {
						success = 5;
						setText("Read in successfully " + txt);
						Thread.sleep(10);
					} else {
						success = 0;
						setText(txt);
						Thread.sleep(10);
					}

				} catch (InterruptedException ex) {
					Thread.currentThread().interrupt(); // very important
					// break;
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			// System.out.println("Shutting down thread");
		}

	}

	public String getHttpPost(String url, List<NameValuePair> params) {
		StringBuilder str = new StringBuilder();
		HttpClient client = new DefaultHttpClient();
		HttpPost httpPost = new HttpPost(url);

		Log.i("Params", params.toString());

		try {
			httpPost.setEntity(new UrlEncodedFormEntity(params));
			HttpResponse response = client.execute(httpPost);
			StatusLine statusLine = response.getStatusLine();
			int statusCode = statusLine.getStatusCode();
			if (statusCode == 200) { // Status OK
				HttpEntity entity = response.getEntity();
				InputStream content = entity.getContent();
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(content));
				String line;
				while ((line = reader.readLine()) != null) {
					str.append(line);
				}
			} else {
				Log.e("Log", "Failed to download result..");
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return str.toString();
	}

	// speak the user text
	public void speakWords(String speech) {
		myTTS.speak(speech, TextToSpeech.QUEUE_FLUSH, null);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {

		if (requestCode == MY_DATA_CHECK_CODE) {
			if (resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) {
				myTTS = new TextToSpeech(this, this);
			} else {
				Intent installTTSIntent = new Intent();
				installTTSIntent
						.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
				startActivity(installTTSIntent);
			}
		}
	}

	@Override
	public void onInit(int initStatus) {
		if (initStatus == TextToSpeech.SUCCESS) {
			if (myTTS.isLanguageAvailable(Locale.US) == TextToSpeech.LANG_AVAILABLE) {
				myTTS.setLanguage(Locale.US);
			}
		} else if (initStatus == TextToSpeech.ERROR) {
			Toast.makeText(this, "Sorry! Text To Speech failed...",
					Toast.LENGTH_LONG).show();
		}
	}

	@Override
	public void onLocationChanged(Location loc) {
		// TODO Auto-generated method stub
		try {
			String lat = Double.toString(loc.getLatitude());
			String lon = Double.toString(loc.getLongitude());
			String spe = Double.toString(loc.getSpeed());

			setText("Latitude : " + lat + "\n" + "Longitude : " + lon + "\n"
					+ "Speed: " + spe);

		} catch (Exception e) {
			// TODO: handle exception
			setText("No Data");
		}
	}

	@Override
	public void onProviderDisabled(String provider) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onProviderEnabled(String provider) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onStatusChanged(String provider, int status, Bundle extras) {
		// TODO Auto-generated method stub

	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		lm.removeUpdates(this);
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1500, 1, this);
	}

}
